import { create } from 'zustand'

interface Honor {
  id: number
  title: string
  description?: string
  memberId: number
  honorType: 'ACHIEVEMENT' | 'AWARD' | 'RECOGNITION'
  dateReceived?: string
  imageUrl?: string
  createdAt: string
  member: {
    id: number
    name: string
    avatar?: string
  }
}

interface HonorStore {
  honors: Honor[]
  statistics: {
    total: number
    byType: { honorType: string; _count: { honorType: number } }[]
    recent: Honor[]
    topMembers: { memberId: number; count: number; member: any }[]
  } | null
  loading: boolean
  error: string | null
  
  // Actions
  fetchHonors: (params?: { memberId?: number; honorType?: string }) => Promise<void>
  fetchHonor: (id: number) => Promise<Honor | null>
  createHonor: (honor: Partial<Honor>) => Promise<void>
  updateHonor: (id: number, honor: Partial<Honor>) => Promise<void>
  deleteHonor: (id: number) => Promise<void>
  fetchStatistics: () => Promise<void>
  searchHonors: (query: string) => Promise<void>
}

export const useHonorStore = create<HonorStore>((set, get) => ({
  honors: [],
  statistics: null,
  loading: false,
  error: null,

  fetchHonors: async (params = {}) => {
    set({ loading: true, error: null })
    try {
      let url = '/api/honors'
      const queryParams = new URLSearchParams()
      if (params.memberId) queryParams.append('memberId', params.memberId.toString())
      if (params.honorType) queryParams.append('honorType', params.honorType)
      
      if (queryParams.toString()) url += `?${queryParams.toString()}`
      
      const response = await fetch(url)
      const data = await response.json()
      if (data.success) {
        set({ honors: data.data.data || [] })
      }
    } catch (error: any) {
      set({ error: error.message })
    } finally {
      set({ loading: false })
    }
  },

  fetchHonor: async (id: number) => {
    try {
      const response = await fetch(`/api/honors/${id}`)
      const data = await response.json()
      if (data.success) {
        return data.data
      }
      return null
    } catch (error: any) {
      set({ error: error.message })
      return null
    }
  },

  createHonor: async (honor) => {
    set({ loading: true, error: null })
    try {
      const response = await fetch('/api/honors', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(honor),
      })
      const data = await response.json()
      if (data.success) {
        await get().fetchHonors()
      }
    } catch (error: any) {
      set({ error: error.message })
    } finally {
      set({ loading: false })
    }
  },

  updateHonor: async (id, honor) => {
    set({ loading: true, error: null })
    try {
      const response = await fetch(`/api/honors/${id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(honor),
      })
      const data = await response.json()
      if (data.success) {
        await get().fetchHonors()
      }
    } catch (error: any) {
      set({ error: error.message })
    } finally {
      set({ loading: false })
    }
  },

  deleteHonor: async (id) => {
    set({ loading: true, error: null })
    try {
      const response = await fetch(`/api/honors/${id}`, {
        method: 'DELETE',
      })
      const data = await response.json()
      if (data.success) {
        await get().fetchHonors()
      }
    } catch (error: any) {
      set({ error: error.message })
    } finally {
      set({ loading: false })
    }
  },

  fetchStatistics: async () => {
    try {
      const response = await fetch('/api/honors/statistics/summary')
      const data = await response.json()
      if (data.success) {
        set({ statistics: data.data })
      }
    } catch (error: any) {
      set({ error: error.message })
    }
  },

  searchHonors: async (query: string) => {
    set({ loading: true, error: null })
    try {
      const response = await fetch(`/api/honors/search?q=${encodeURIComponent(query)}`)
      const data = await response.json()
      if (data.success) {
        set({ honors: data.data.data || [] })
      }
    } catch (error: any) {
      set({ error: error.message })
    } finally {
      set({ loading: false })
    }
  },
}))